<template>
  <view class="container">
    <!-- 电站容量 -->
    <view class="form-item">
      <text class="label">电站容量(W)</text>
      <input 
        class="input" 
        type="number" 
        v-model="formData.totalpower"
        placeholder="请输入电站容量"
      />
    </view>

    <!-- 客户信息 -->
    <view class="form-item">
      <text class="label">客户姓名</text>
      <input 
        class="input" 
        v-model="formData.guestname"
        placeholder="请输入客户姓名"
      />
    </view>

    <!-- 联系方式 -->
    <view class="form-item">
      <text class="label">联系电话</text>
      <input
        class="input"
        type="number"
        v-model="formData.phone"
        placeholder="请输入联系电话"
      />
    </view>

    <!-- 省市区选择 -->
	<view class="uni-title uni-common-pl labelForItem">地区选择:</view>
	<view class="uni-list areaSelection">
	  <view class="uni-list-cell">
		<view class="uni-list-cell-db">
			<br>
		  <picker class="pickerMulti" mode="multiSelector" @columnchange="handleColumnChange" @change="handlePickerChange"
			:value="value" :range="range" @click="fetchAreas()" >
			<view class="uni-input pickerMultiValue">
			  {{range[0][value[0]]}}，{{range[1][value[1]]}}，{{range[2][value[2]]}}
			</view>
		  </picker>
		</view>
	  </view>
	</view>

    <!-- 详细地址 -->
    <view class="form-item">
      <text class="label">详细地址</text>
      <input
        class="input"
        v-model="formData.address"
        placeholder="请输入详细地址"
      />
    </view>

    <!-- 坐标输入 -->
	<view class="form-item" @click="chooseLocation">
		<text class="label">位置：</text>                                                     
		<view v-if="formData.latitude && formData.longitude">
			<map :longitude="formData.longitude" :latitude="formData.latitude" scale="15" show-compass show-scale @click="chooseLocation"></map>
		</view>
		<view v-else>
			<map :longitude="location.longitude" :latitude="location.latitude" scale="15" show-compass show-scale @click="chooseLocation"></map>
		</view>
		<view class="map-overlay"></view>
	</view>


    <!-- 图片上传 -->
	<view class="upload-header">
		<text class="label">图片上传：</text>
	</view>
	<view class="upload-grid">
		<view v-for="(img, index) in previewImage" :key="index" class="image-wrapper">
		  <image :src="img" class="uploaded-image" mode="aspectFill" />
		  <view class="delete-icon" @click="removeImage(index)">✖</view>
		</view>
		<view class="upload-add" @click="tupian">
		  <image src="/static/camera-icon.png" class="camera-icon" mode="aspectFit" />
		</view>
	</view>

    <!-- 提交按钮 -->
    <button class="submit-btn" @click="handleSubmit">提交新建</button>
  </view>
</template>



<script>
import request from '@/utils/request.js'; 
import { getAccessToken } from '@/utils/auth';	

export default {
	
  data() {
    return {
	  location:{
		longitude:'',
		latitude:'',
	  },
      token: '',
      formData: {
        totalpower: '',
        guestname: '',
        phone: '',
		provinceId:'',
		cityId:'',
        areaId: '',
        address: '',
        source: '1',
        latitude: '',
        longitude: '',
        status: 1,
        locationPicUrls: [],
      },
      provinces: [],
      cities: {},
      areas: {},
      range: [[], [], []],
      value: [0, 0, 0],
      selectedText: '',
	  previewImage:[],
    }
  },
  async onLoad() {
    this.token = await getAccessToken('token')
    this.fetchAreas()
	this.initialMap()
  },
  methods: {
    // 省市区数据获取（保持你提供的代码不变）
    async fetchAreas() {
    	try {
    		const response = await request({
    		  url: "/system/area/tree",
    		  method: 'GET',
    		  headers: { Authorization: `Bearer ${this.token}` }
    		});
    
    		const areaData = response.data;
    		// 提取省份
    		this.provinces = areaData.map(province => ({
    		  id: province.id,
    		  name: province.name,
    		}));
    		// 初始化存储城市和区域的对象
    		this.cities = {};
    		this.areas = {};
    	
    		// 提取市、区数据
    		areaData.forEach((province) => {
    		  this.cities[province.id] = province.children.map((city) => ({
    			id: city.id,
    			name: city.name,
    		  }));
    		  
    		  province.children.forEach((city) => {
    			this.areas[city.id] = city.children.map((area) => ({
    			  id: area.id,
    			  name: area.name,
    			}));
    		  });
    		});
    
    		this.range[0] = this.provinces.map(p => p.name);
    		// 初始化第2列和第3列数据
    		this.range[1] = this.cities[this.provinces[0].id].map(c => c.name);
    		this.range[2] = this.areas[this.cities[this.provinces[0].id][0].id].map(a => a.name);
    	} catch (error) {
    	}
    },
	handleColumnChange(event) {
	   const { column, value } = event.detail;
	     // 当省份变更时，重置下级ID
	     if (column === 0) {
	       this.formData.cityId = null;  // 清空城市ID
	       this.formData.areaId = null;  // 清空区域ID
	     }
	     
	     // 当城市变更时，重置区域ID
	     if (column === 1) {
	       this.formData.areaId = null;
	     }
		 
	   if (column === 0) {
		 // 修改第1列（省份），需要更新第2、3列
		 const selectedProvinceId = this.provinces[value].id;
		 this.range[1] = this.cities[selectedProvinceId].map(city => city.name);
		 this.range[2] = this.cities[selectedProvinceId].length > 0
		   ? this.areas[this.cities[selectedProvinceId][0].id].map(area => area.name)
		   : [];
		 this.value[1] = 0;
		 this.value[2] = 0;
	   } else if (column === 1) {
		 // 修改第2列（城市），需要更新第3列
		 const selectedCityId = this.cities[this.provinces[this.value[0]].id][value].id;
		 this.range[2] = this.areas[selectedCityId].map(area => area.name);
		 this.value[2] = 0;
	   }
	
	   // 更新 value 的当前索引
	   this.value[column] = value;
	   
		console.log('当前选中索引:', this.value);
	   this.$forceUpdate();
	 },
	 handlePickerChange(event) {
	   const pickerValue = event.detail.value;
	   const selectedProvince = this.provinces[pickerValue[0]];
	   const selectedCity = this.cities[selectedProvince.id][pickerValue[1]];
	   const selectedArea = this.areas[selectedCity.id][pickerValue[2]];
	   this.formData.provinceId = this.provinces[pickerValue[0]].id;
	   this.formData.cityId = this.cities[selectedProvince.id][pickerValue[1]].id;
	   this.formData.areaId = this.areas[selectedCity.id][pickerValue[2]].id;
		console.log("选中的区",this.areas[selectedCity.id][pickerValue[2]]);
	   // 设置选中的文字
	   this.selectedText = `${selectedProvince.name}-${selectedCity.name}-${selectedArea.name}`;
	 },
	
	//图片
	
	tupian() {
	  uni.chooseImage({
	    success: (chooseImageRes) => {
	      const tempFilePaths = chooseImageRes.tempFilePaths;
	      console.log("缩略图", this.previewImage);
	
	      // 遍历所有选择的文件
	      tempFilePaths.forEach((filePath) => { // 新增：循环每个文件
	        uni.uploadFile({
	          url: 'http://123.60.139.112:48080/admin-api/infra/file/upload',
	          header: { Authorization: `Bearer ${this.token}` },
	          filePath: filePath, // 修改：用循环中的 filePath
	          name: 'file',
	          formData: { 'user': 'test' },
	          success: (res) => {
	            console.log('Success:', res.statusCode, res.data);
	            try {
	              const responseData = JSON.parse(res.data);
	              if (responseData.code === 0) {
	                // 修改：用 push 追加而非直接赋值
	                this.formData.locationPicUrls.push(responseData.data);
	                this.previewImage = [...this.previewImage, responseData.data]; // 追加新图片
	                console.log('新增 URL:', responseData.data);
	              } else {
	                console.error('上传失败:', responseData.msg);
	              }
	            } catch (error) {
	              console.error('解析响应失败:', error);
	            }
	          },
	          fail: (err) => {
	            console.error('Fail:', err.errMsg);
	          },
	          complete: (res) => {
	            console.log('Complete:', res);
	          }
	        });
	      });
	    }
	  });
	},
	removeImage(index) {
	  this.previewImage.splice(index, 1);
	  this.formData.locationPicUrls.splice(index, 1);
	},

	//地址选择
	chooseLocation() {
		uni.chooseLocation({
			success: (res) => {
			this.formData.latitude = res.latitude;
			this.formData.longitude = res.longitude;
			},
			fail: (err) => {
				uni.showToast({
					title: '位置选择失败',
					icon: 'none'
				});
			}
		});
	},
	initialMap() {
	  uni.getLocation({
		type: 'wgs84', // 返回可以用于 uni.openLocation 的经纬度
		success: (res) => {  // ✅ 使用箭头函数，保持 this 上下文
		  this.location.longitude = res.longitude;
		  this.location.latitude = res.latitude;
		  console.log('当前位置的经度：' + res.longitude);
		  console.log('当前位置的纬度：' + res.latitude);
		},
		fail: (err) => {
		  console.error('获取位置失败：', err);
		}
	  });
	},

    // 表单提交
    async handleSubmit() {
      try {
        // 表单验证
		console.log('[提交前原始数据]', JSON.parse(JSON.stringify(this.formData)))
		const submitData = {
			totalpower: String(this.formData.totalpower), // 明确类型转换
			guestname: this.formData.guestname.trim(),
			phone: this.formData.phone,
			areaId: Number(this.formData.areaId), // 确保数值类型
			address: this.formData.address.trim(),
			source: this.formData.source,
			latitude: String(this.formData.latitude),
			longitude: String(this.formData.longitude),
			status: Number(this.formData.status),
			locationPicUrls: this.formData.locationPicUrls.map(url => url.trim()) // 清理URL空格
		}
        console.log('[转换后提交数据]', submitData)
		console.log('[数据类型验证]', {
		  areaIdType: typeof submitData.areaId,
		  statusType: typeof submitData.status,
		  picUrlsType: Array.isArray(submitData.locationPicUrls)
		})

        const response = await request({
          url: '/oper/station/create',
          method: 'POST',
          headers: { Authorization: `Bearer ${this.token}`,
		   'Content-Type': 'application/json'},
          data: submitData,
        })
        console.log(submitData)
        uni.showToast({ title: '创建成功' })
        setTimeout(() => uni.navigateBack(), 1500)
      } catch (error) {
        console.error('提交失败:', error)
      }
    },
  }
} 
</script>

<style>
/* 样式部分根据实际需求调整 */
.container {
  padding: 24rpx;
  background-color: white;
}

.form-item {
  margin-bottom: 32rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  margin-bottom: 16rpx;
  font-weight: bolder;
  
}
.picker{
  padding: 0 20rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  height: 80rpx;
  align-items: center;
}
.input {
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
}
/*省市区选择*/
.areaSelection{
	display: flex;
    justify-content: center;
	width: 100%;
}
.pickerMulti {
  width: 100%;              /* 🎯 宽度占容器的80% */
  text-align: center;      /* 🎯 内容文字居中 */
}

.pickerMultiValue {
  padding: 12px 16px;
  border: 1px solid #e5e5e5;
  border-radius: 8px;
  min-width: 300px;
  width: 100%;             /* 🎯 让 picker 完全占据 .pickerMulti 的宽度 */
  font-size: 16px;         /* 🎨 设置字体大小（如果不自适应） */
  box-sizing: border-box;
}

.submit-btn {
  margin-top: 48rpx;
  background: #007AFF;
  color: white;
}


</style>

<style lang="scss" scoped>
.upload-header {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-top: 10rpx;

  .image-wrapper {
    position: relative;
    width: 100%;
    aspect-ratio: 1 / 1;

    .uploaded-image {
      width: 100%;
      height: 100%;
      border-radius: 5rpx;
      object-fit: cover;
      border: 1rpx solid #ddd;
    }

    .delete-icon {
      position: absolute;
      top: 5rpx;
      right: 5rpx;
      width: 36rpx;
      height: 36rpx;
      background-color: rgba(0, 0, 0, 0.6);
      color: #fff;
      text-align: center;
      line-height: 36rpx;
      border-radius: 50%;
      cursor: pointer;
      font-size: 24rpx;
    }
  }

  .upload-add {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    aspect-ratio: 1 / 1;
    border: 2rpx dashed #aaa;
    border-radius: 5rpx;
    cursor: pointer;

    .camera-icon {
      width: 80rpx;
      height: 80rpx;
    }
  }
}
.map-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0);
  z-index: 1;
  pointer-events: none; /* 保证点击事件可以传递到 map */
}
</style>
